package com.zzx.auth.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zzx.auth.biz.SysUserBiz;
import com.zzx.auth.mapper.SysUserRoleMapper;
import com.zzx.auth.model.SysUser;
import com.zzx.auth.model.SysUserRole;
import com.zzx.auth.model.result.CommonResultBean;
import com.zzx.common.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制层
 */
@RestController
@RequestMapping("/oauth")
public class UserController {


    @Autowired
    private TokenStore                           tokenStore;

    @Autowired
    private StringRedisTemplate                  redisTemplate;

    @Autowired
    private TokenEndpoint                        tokenEndpoint;

    @Autowired
    private CheckTokenEndpoint                   checkTokenEndpoint;

    @Autowired
    private SysUserBiz                           sysUserBiz;

    @Autowired
    private SysUserRoleMapper                    sysUserRoleMapper;

    /**
     * 获取用户token（登录）
     *
     * @param principal      权限对象
     * @param principal      client_id 与 client_secret对应数据库中的client_secret入参用DES_CBC_Encrypt("863486267",WEB_KEY)加密，数据库中需要用SecurityUtils.encryptPassword("admin")加密
     * @param parameters     前端请求参数（http://localhost:8890/oauth/token?grant_type=password&username=18628395777&password=394DDBA02D15E820959B46AF6BCE45CA&client_id=admin&client_secret=F3573328CEB59294）
     * @return               用户token
     * @throws HttpRequestMethodNotSupportedException
     */
    @RequestMapping("/token")
    public CommonResultBean<Map<String, Object>> customPostAccessToken(Principal principal,
                                                                       @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        Map<String, Object> data = new HashMap<>(4);
        data.put("token", accessToken.getValue());
        data.put("nickName", accessToken.getAdditionalInformation().get("nickName"));
        data.put("userType", accessToken.getAdditionalInformation().get("user_type"));
        if (accessToken.getRefreshToken() != null) {
            data.put("refreshToken", accessToken.getRefreshToken().getValue());
        }
        // 根据需要添加其他信息....
//        System.out.println(SecurityUtils.encryptPassword("admin"));
        return new CommonResultBean<>(true, "成功", data);
    }

    /**
     *  登出
     * @param authHeader
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/logout")
    public ResponseEntity<String> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader,
                                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(authHeader)) {
            return new ResponseEntity<>("success", HttpStatus.OK);
        }

        String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, "").trim();
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
        if (accessToken == null || StringUtils.isEmpty(accessToken.getValue())) {
            return new ResponseEntity<>("非法Token或Token已过期", HttpStatus.OK);
        }
        // 删除现有用户 token
        tokenStore.removeAccessToken(accessToken);
        return new ResponseEntity<>("success", HttpStatus.OK);
    }

    /**
     * 添加用户
     *
     * @param sysUser           系统用户（{"password":"863486267","deptId":"796011552938393600","userName":"18628395778","nickName":"猪哥哥","userType":"1","phone":"18628395778"}）
     * @return                  CommonResultBean
     */
    @PostMapping("/user/register")
    @Transactional
    public CommonResultBean insertUser(@RequestBody SysUser sysUser) {
        sysUser.setUserId(String.valueOf(IdWorker.getId()));
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUserBiz.save(sysUser);
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(1L);
        sysUserRole.setCreateTime(new Date());
        sysUserRoleMapper.insert(sysUserRole);
        return new CommonResultBean<>(true, "成功", null);
    }

    /**
     * 删除用户
     *
     * @param id              用户id
     * @return                CommonResultBean
     */
    @PostMapping("/user/delete")
    public CommonResultBean logicDelete(String id) {
        sysUserBiz.removeById(id);
        return new CommonResultBean<>(true, "成功", null);
    }
}
